
const mysql = require('mysql')
import { dbConfig } from "./dbConfig"
/* const dbConfig = {
  host: '',  // 连接地址
  user: '',    //用户名
  password: '',  //密码
  port: 3306,   //端口号
  database: ''   //数据库名
} */
let pool = mysql.createPool(dbConfig)
// 执行数据库
const execSql = (sql: string, values = []) => {
  return new Promise((resolve, reject) => {
    pool.getConnection((err: any, conn: any) => {
      if (err) {
        //连接错误
        reject(err)
      } else {
        //连接成功
        // sql语句中使用?占位符, values传递是个数组
        conn.query(sql, values, (err: any, data: any) => {
          if (err) {
            //操作失败
            reject(err)
          } else {
            resolve(data)
          }
        })
      }
      // 当连接不再使用时，用conn对象的release方法将其归还到连接池中
      conn.release()
    })
  })
}

class DbConnect {
  private connection: any;
  constructor(conn: any) {
    this.connection = conn;
  }

  beginTransaction() {
    if (this.connection) {
      this.connection.beginTransaction();
    }
  }

  commit() {
    if (this.connection) {
      this.connection.commit();
    }

  }

  rollback() {
    if (this.connection) {
      this.connection.rollback();
    }

  }

  execSql(sql: string, values = []) {
    return new Promise((resolve, reject) => {
      this.connection.query(sql, values, (err: any, data: any) => {
        if (err) {
          //操作失败
          reject(err)
        } else {
          resolve(data)
        }
      })
    })
  }
  close() {
    if (this.connection) {
      this.connection.release();
    }
  }
}
module.exports = {
  execSql,
  getConnection() {
    return new Promise((resolve, reject) => {
      pool.getConnection((err: any, conn: any) => {
        if (err) {
          //连接错误
          reject(err)
        } else {
          resolve(new DbConnect(conn));
        }
      })
    })
  }

}
